<template>
  <div class="page">
    <div class="page_content">
      <div class="page_cnt">
        <div class="header">
          <div class="tit">
            <span
              v-for="(item, index) in tabs"
              :key="index"
              @click="handleClick(index)"
              :class="{ blue: activeIndex === index }"
            >
              {{ item }}
            </span>
          </div>
          <div class="search">
            <el-input
              v-model="searchTopic"
              style="width: 240px; border-radius: 20px;"
              placeholder="搜索话题"
              :suffix-icon="Search"
            />
          </div>
        </div>

        <div class="content">
          <div class="items">
            <div class="item" 
                v-for="(item, index) in processedContent" 
                :key="index"
                
            >
              <router-link :to="{ name: 'qa-detail', query: { id: item.post_id } }">
                <div class="item_top">
                  <span class="top_tag" v-if="item.is_top">置顶</span>
                </div>
                <div class="item_main">
                  <div style="display: flex; align-items: center; margin-top:-20px">
                    <div style="margin-left:40px">
                      <img :src="item.img_url" class="avatar" />
                      <div class="username">{{ item.username }}</div>
                    </div>
                    <div class="buble"
                    :class="{ 'own-post': item.username == username }">
                      <a class="post_title">{{ item.post_title }}</a>
                    </div>
                  </div>
                  <div class="reply_count">
                    <span 
                      class="delete-btn" 
                      v-if="item.username == username" 
                      @click.stop.prevent="deletePost(item.post_id)"
                    >删除</span>
                    <span class="postbtn">{{ item.comment_cnt }} 回复</span>
                  </div>
                </div>
              </router-link>
            </div>
          </div>

          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 40]"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="dataCnt"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <div class="page_topic">
        <div class="post_topic">
          <h2><span @click="checkLogin">发布话题</span></h2>
        </div>
        <div class="hot_topic">
          <h2>热门标签</h2>
          <div class="topics">
            <a v-for="(item, index) in hotTopics" :key="index">{{ item.name }}</a>
          </div>
        </div>
      </div>

      <!-- 发布话题弹窗 -->
      <el-dialog v-model="dialogVisible" title="发布话题" width="1000px">
        <el-form
          ref="ruleFormRef"
          :model="topicForm"
          :rules="rules"
          label-width="auto"
          status-icon
        >
          <el-form-item label="话题名称：" prop="name">
            <el-input
              v-model="topicForm.name"
              maxlength="30"
              show-word-limit
              placeholder="请输入话题名称"
              style="width: 600px; height: 40px;"
            />
          </el-form-item>

          <el-form-item label="内容：" prop="content">
            <QuillEditor v-model="topicForm.content" style="width: 800px; height: 400px;" />
          </el-form-item>

          <el-form-item label="话题类型：" prop="topicType">
            <el-select
              v-model="topicForm.topicType"
              placeholder="请选择话题类型"
              style="width: 240px;"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="专业方向：" prop="technology">
            <el-select
              v-model="topicForm.technology"
              placeholder="请选择专业方向"
              style="width: 240px;"
            >
              <el-option
                v-for="item in techOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import QuillEditor from '../components/QuillEditor.vue'
import { postTopic, getNewTopic, getHotTopic, getTopic} from '../services/topic'
import { getDirections,  } from "@/services/api";
import { ElMessage,ElMessageBox } from 'element-plus';
import api from '@/services/api';

// 状态管理
const router = useRouter()
const username = ref(localStorage.getItem('username'))
// 搜索内容
const searchTopic = ref('')

// 话题列表
const content = ref([])
const currentPage = ref(1)
const pageSize = ref(4)
const dataCnt = ref(0)

// 标签和导航
const tabs = ['最新回复', '热门话题', '技术分享', '通知公告']
const activeIndex = ref(0)

// 热门标签
const hotTopics = ref([])

// 专业方向 options
const techOptions = ref([])

// 发布话题弹窗控制
const dialogVisible = ref(false)
// 删除评论
const deletePost = async (commentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response = await api.delete(`/youxich/home/topic/${commentId}`);
    if (response.data.status === 1) {
      ElMessage.success("删除成功！");
    } else {
      ElMessage.warning(response.data.msg || "删除失败");
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error("删除失败：" + (err.response?.data?.msg || err.message));
    }
  }
};

// 发布话题表单
const topicForm = reactive({
  name: '',
  content: '',
  topicType: '',
  technology: '',
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入话题名称', trigger: 'blur' },
    { min: 3, max: 30, message: '长度应为3到30个字符', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入话题内容', trigger: 'blur' },
  ],
  topicType: [
    { required: true, message: '请选择话题类型', trigger: 'change' },
  ],
  technology: [
    { required: true, message: '请选择专业方向', trigger: 'change' },
  ],
}

// 话题类型
const typeOptions = [
  { value: 'discussion', label: '技术分享' },
  { value: 'notice', label: '通知公告' },
  { value: 'other', label: '其他' },
]

// 处理置顶话题优先展示
const processedContent = computed(() => {
  const topped = content.value.filter(item => item.is_top)
  const normal = content.value.filter(item => !item.is_top)
  return [...topped, ...normal]
})

// 方法：分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getTopicData(activeIndex.value)
}

// 方法：页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTopicData(activeIndex.value)
}

// 方法：点击标签切换
const handleClick = (index) => {
  activeIndex.value = index
  getTopicData(index)
}

// 方法：拉取话题列表
const getTopicData = (index) => {
  if (index === 0) {
    getNewTopic(1, currentPage.value, pageSize.value).then(res => {
      dataCnt.value = res.data.data.page_cnt
      content.value = res.data.data.postList
    })
  } else if (index === 1) {
    getHotTopic(1, currentPage.value, pageSize.value).then(res => {
      dataCnt.value = res.data.data.page_cnt
      content.value = res.data.data.postList
    })
  } else if (index === 2) {
    getTopic(1, currentPage.value, pageSize.value, 'discussion').then(res => {
      dataCnt.value = res.data.data.page_cnt
      content.value = res.data.data.postList
    })
  } else if (index === 3) {
    getTopic(1, currentPage.value, pageSize.value, 'notice').then(res => {
      dataCnt.value = res.data.data.page_cnt
      content.value = res.data.data.postList
    })
  }
}

// 方法：发布话题
const submitForm = () => {
  const form = ruleFormRef.value
  form.validate((valid) => {
    if (valid) {
      const payload = {
        publisher_id: localStorage.getItem('id'),
        course_id: 1,
        post_title: topicForm.name,
        post_content: topicForm.content,
        post_type: topicForm.topicType,
        direction_id: topicForm.technology,
      }
      postTopic(payload).then(res => {
        if (res.data.status === 1) {
          ElMessage.success('发布成功')
          dialogVisible.value = false
          getTopicData(activeIndex.value)
        } else {
          ElMessage.error('发布失败：' + res.data.message)
        }
      }).catch(/* eslint-disable */ err => {  // 添加禁用注释
        ElMessage.error('网络错误')
      })
    }
  })
}

// 方法：重置表单
const resetForm = () => {
  dialogVisible.value = false
}

// 方法：登录校验
const checkLogin = () => {
  const token = localStorage.getItem('token')
  if (token) {
    dialogVisible.value = true
  } else {
    ElMessage.error('未登录，请先登录')
    router.push('/login')
  }
}

// 方法：拉取方向列表
const getDirectionList = () => {
  getDirections().then(res => {
    techOptions.value = res.data.data.map(item => ({
      value: item.direction_id,
      label: item.direction_title
    }))
    hotTopics.value = res.data.data.map(item => ({
      name: item.direction_title
    }))
  }).catch(err => {
    console.error(err)
  })
}

// 生命周期
onMounted(() => {
  getDirectionList()
  getTopicData(activeIndex.value)
})

// 引用表单
const ruleFormRef = ref()
</script>

<style scoped>
@import "@/assets/css/QA.css";

.blue {
  color: rgba(68, 103, 182);
  font-weight: bold;
}

.page{
    display: flex;
    justify-content: center;

}
.own-post {
  background-color: rgba(90, 162, 189, 0.075); /* 浅蓝背景 */
  border-left: 5px solid #4680ff;
}
.delete-btn {
  margin-right: 10px;
  cursor: pointer;
}
.delete-btn:hover{
  text-decoration: underline;
}
.postbtn:hover{
  text-decoration: underline;
}
  .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    border: 2px solid #CACCC7;
  }
</style>
